const vosk = require("vosk");
const fs = require("fs");
const path = require("path");
const process = require("process");

const getAudioStream = (rec, callBack) => {
  let currentRecorder;
  let audioStream;
  //  SoX 的可执行文件路径为：
  const SOX_PATH = path.join(__dirname, "./sox-14.4.1");
  // 检查SoX路径
  if (!fs.existsSync(SOX_PATH)) {
    throw new Error(
      `SoX可执行文件不存在: ${SOX_PATH}\n请确保sox-14.4.1目录包含以下文件:\n- sox.exe\n- 所有必需的DLL文件`
    );
  }
  // 将 SoX 路径添加到当前进程的 PATH 环境变量中
  process.env.PATH = process.env.PATH + path.delimiter + SOX_PATH;
  // 设置录音配置
  const recorder = require("node-record-lpcm16");
  currentRecorder = recorder.record({
    sampleRate: 16000, // 采样率
    channels: 1, // 单声道
    device: "default", // 默认录音设备
    verbose: process.env.DEBUG === "record", // 调试模式
  });
  console.log("初始化语音识别系统...");
  audioStream = currentRecorder.stream();
  //监听录音 生成音频流
  audioStream.on("data", (data) => {
    //data 是16位PCM数据
    // 识别音频流
    if (rec.acceptWaveform(data)) {
      const result = rec.result();
      if (result.text.trim().length > 0) {
        callBack(result.text);
      }
    }
  });

  audioStream.on("error", (err) => {
    console.error("录音错误:", err);
  });
  // 程序退出处理
  process.on("SIGINT", () => {
    const finalResult = rec.finalResult();
    if (finalResult.text.trim().length > 0) {
      console.log("\n最终识别结果:", finalResult.text);
    }
    rec.free();
    process.exit(0);
  });
  return function stopRecording() {
    if (currentRecorder) {
      currentRecorder.stop();
      audioStream.removeAllListeners(); // 清除所有事件监听
      audioStream.destroy(); //
      audioStream = null;
      currentRecorder = null;
    }
  }
};


/**
 * 实时语音识别函数
 * 使用Vosk语音识别引擎和SoX进行音频采集
 */

function recognizeLiveAudio(AudioStreamFn, callBack) {
  // 语音识别模型 路径
  const MODEL_PATH = path.join(__dirname, "./vosk-model-small-cn-0.22");
  // 检查模型路径
  if (!fs.existsSync(MODEL_PATH)) {
    throw new Error(`Vosk模型目录不存在: ${MODEL_PATH}`);
  }

  // 初始化语音识别器
  const model = new vosk.Model(MODEL_PATH);
  const rec = new vosk.Recognizer({ model, sampleRate: 16000 });
  console.log("模型加载完成:", MODEL_PATH);
  return rec
}
module.exports = {
  recognizeLiveAudio,
  getAudioStream,
};
